package com.example.canal.utils;

/**
 * @PROJECT_NAME: canal
 * @DESCRIPTION:
 * @USER: taik
 * @DATE: 2023/2/17 18:50
 */


import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import com.example.canal.dao.EsOrderDao;
import com.example.canal.entity.CanalMessage;
import com.example.canal.entity.Order;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;


/**
 * 监听MQ获取Canal增量的数据消息
 */
@Component
@Slf4j
@RequiredArgsConstructor
public class CanalRabbitMQListener {
    @Autowired
    private EsOrderDao orderDao;

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(value = "canal.queue", durable = "true"),
                    exchange = @Exchange(value = "canal.exchange"),
                    key = "canal.routing.key"
            )
    })
    public void handleDataChange(String message) {
        //将message转换为CanalMessage
        /*log.info("message:"+message);*/

        CanalMessage canalMessage = JSONUtil.toBean(message, CanalMessage.class);
        String tableName = canalMessage.getTable();
        /*log.info("data:"+canalMessage.getData());*/
        /*log.info("Canal 监听 {} 发生变化；明细：{}", tableName, message);*/
        //TODO 业务逻辑自己完善...............
        List<JSONObject> data = canalMessage.getData();
        String type = canalMessage.getType();
        log.info("type:"+type);
        for(JSONObject jsonObject: data) {
            Order order = JSONUtil.toBean(jsonObject, Order.class);
            log.info("order:"+order);
            orderDao.save(order);
        }
    }
}


